<template>
  <div class="chat-container">
    <!-- 左侧会话列表 -->
    <div class="conversation-sidebar">
      <div class="sidebar-header">
        <h3>会话列表</h3>
        <el-button type="primary" size="small" @click="startNewConversation">新建会话</el-button>
      </div>
      
      <div class="conversation-list">
        <div 
          v-for="conv in conversations" 
          :key="conv.id"
          :class="['conversation-item', { active: activeConversationId === conv.id }]"
          @click="switchConversation(conv.id)"
        >
          <div class="conversation-info">
            <div class="conversation-title">会话 {{ conv.id }}</div>
            <div class="conversation-meta">
              <span class="status" :class="conv.status">{{ getStatusText(conv.status) }}</span>
              <span class="time">{{ formatTime(conv.createTime) }}</span>
            </div>
          </div>
        </div>
        
        <div v-if="conversations.length === 0" class="empty-state">
          暂无会话记录
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <!-- 聊天输入框 -->
      <div class="chat-header">
        <el-input 
          v-model="questionInput" 
          placeholder="请输入您的问题..." 
          clearable 
          @keyup.enter="submitQuestion"
        />
        <el-button type="primary" @click="submitQuestion">提问</el-button>
      </div>

      <!-- 聊天消息区域 -->
      <div class="chat-body" ref="chatBody">
        <div v-if="!activeConversationId" class="welcome-message">
          <p>👋 欢迎使用农业专家问答系统</p>
          <p>请选择一个会话或开始新的提问</p>
        </div>
        
        <div v-else-if="messages.length === 0" class="no-messages">
          <p>该会话暂无消息记录</p>
        </div>
        
        <div v-else>
          <div
            v-for="(msg, index) in messages"
            :key="index"
            class="chat-message"
            :class="msg.role"
            @click="handleClickMessage(msg)"
          >
            <div class="sender">{{ msg.role === 'asker' ? '用户' : '专家' }}</div>
            <div class="bubble">{{ msg.message }}</div>
            <div class="message-time">{{ formatTime(msg.sendTime) }}</div>

            <!-- 专家回复框 -->
            <div
              class="reply-box"
              v-if="isExpert && replyTarget?.id === msg.id && msg.role === 'asker'"
              @click.stop
            >
              <el-input
                v-model="answerInput"
                placeholder="请输入您的回答..."
                type="textarea"
                :rows="3"
                clearable
                @click.stop
              />
              <div class="reply-actions">
                <el-button @click="cancelReply">取消</el-button>
                <el-button type="success" @click="submitAnswerTo(msg)">提交回答</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  listConversationRecords, 
  addConversationRecord, 
  addConversation,
  updateConversationExpert,
  listConversation
} from '@/api/agriculture/guo/conversation/chat'

// 参数设置
const currentUserId = 101        // 当前登录用户ID
const isExpert = true            // 是否是专家用户

// 数据绑定
const conversations = ref([])     // 会话列表
const activeConversationId = ref(null) // 当前激活的会话ID（数字类型）
const messages = ref([])
const questionInput = ref('')
const answerInput = ref('')
const replyTarget = ref(null)
const chatBody = ref(null)

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'open': '待回复',
    'answered': '已回复',
    'closed': '已关闭'
  }
  return statusMap[status] || status
}

// 获取会话列表
const fetchConversations = async () => {
  try {
    // 设置查询参数，获取最新的20条记录
    const res = await listConversation({
      pageNum: 1,
      pageSize: 20,  // 显示20个会话
      orderByColumn: 'create_time', // 按创建时间排序
      isAsc: 'desc'  // 降序排列，最新的在前面
    })
    console.log('📋 会话列表返回：', res)
    
    const list = res?.data?.rows || res?.rows || res?.data || res || []
    
    // 再次确保按ID降序排列（ID越大越新）
    conversations.value = list
      .sort((a, b) => b.id - a.id)
      .slice(0, 20) // 只保留前20个
    
    console.log('📋 处理后的会话列表：', conversations.value)
  } catch (error) {
    console.error('❌ 获取会话列表失败:', error)
    ElMessage.error('获取会话列表失败')
  }
}

// 拉取对话记录
const fetchMessages = async (conversationId) => {
  if (!conversationId) {
    messages.value = []
    return
  }
  
  try {
    console.log('🔍 正在获取会话记录，conversationId:', conversationId)
    
    const res = await listConversationRecords({ conversationId })
    console.log('💬 消息记录返回：', res)
    
    const list = res?.data?.rows || res?.rows || res?.data || res || []
    messages.value = list.sort((a, b) => new Date(a.sendTime) - new Date(b.sendTime)) // 按时间升序排列
    
    console.log('💬 处理后的消息列表：', messages.value)
    
    scrollToBottom()
  } catch (error) {
    console.error('❌ 获取消息记录失败:', error)
    ElMessage.error('获取消息记录失败')
  }
}

// 切换会话
const switchConversation = async (conversationId) => {
  console.log('🔄 切换会话到:', conversationId)
  activeConversationId.value = conversationId
  replyTarget.value = null // 清除回复目标
  await fetchMessages(conversationId)
}

// 开始新会话
const startNewConversation = () => {
  activeConversationId.value = null
  messages.value = []
  replyTarget.value = null
  questionInput.value = ''
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatBody.value) {
      chatBody.value.scrollTop = chatBody.value.scrollHeight
    }
  })
}

// 提交提问 - 创建新会话
const submitQuestion = async () => {
  if (!questionInput.value.trim()) {
    ElMessage.warning('请输入问题内容')
    return
  }
  
  try {
    // 1. 创建新会话
    const conversationRes = await addConversation({
      askerId: currentUserId,
      status: 'open'
    })
    
    console.log('✅ 创建会话返回：', conversationRes)
    
    // 获取新创建的会话ID - 多种可能的返回格式
    let newConversationId = null
    if (conversationRes.data?.id) {
      newConversationId = conversationRes.data.id
    } else if (conversationRes.data?.data?.id) {
      newConversationId = conversationRes.data.data.id
    } else if (conversationRes.id) {
      newConversationId = conversationRes.id
    }
    
    console.log('🆔 提取的会话ID:', newConversationId)
    
    if (!newConversationId) {
      throw new Error('无法获取新创建的会话ID，返回数据格式：' + JSON.stringify(conversationRes))
    }
    
    // 2. 添加问题记录
    await addConversationRecord({
      conversationId: newConversationId,
      senderId: currentUserId,
      role: 'asker',
      message: questionInput.value
    })
    
    // 3. 立即将新会话添加到列表顶部（优化用户体验）
    const newConversation = {
      id: newConversationId,
      askerId: currentUserId,
      expertId: null,
      status: 'open',
      createTime: new Date().toISOString()
    }
    
    // 将新会话添加到列表最前面，并保持最多20个
    conversations.value = [newConversation, ...conversations.value.slice(0, 19)]
    
    // 4. 更新当前会话
    activeConversationId.value = newConversationId
    questionInput.value = ''
    
    // 5. 刷新消息列表
    await fetchMessages(newConversationId)
    
    // 6. 后台刷新完整的会话列表（确保数据同步）
    fetchConversations()
    
    ElMessage.success('提问成功')
    
  } catch (error) {
    console.error('❌ 提交问题失败:', error)
    ElMessage.error('提交问题失败：' + error.message)
  }
}

// 点击某条消息：显示回答框（仅专家回答用户提问）
const handleClickMessage = (msg) => {
  if (isExpert && msg.role === 'asker') {
    replyTarget.value = replyTarget.value?.id === msg.id ? null : msg
    answerInput.value = ''
    
    // 如果打开了回复框，自动聚焦到输入框
    if (replyTarget.value) {
      nextTick(() => {
        const textarea = document.querySelector('.reply-box textarea')
        if (textarea) {
          textarea.focus()
        }
      })
    }
  }
}

// 取消回复
const cancelReply = () => {
  replyTarget.value = null
  answerInput.value = ''
}

// 提交专家回答
const submitAnswerTo = async (msg) => {
  if (!answerInput.value.trim()) {
    ElMessage.warning('请输入回答内容')
    return
  }
  
  try {
    // 1. 添加回答记录
    await addConversationRecord({
      conversationId: activeConversationId.value,
      senderId: currentUserId,
      role: 'expert',
      message: answerInput.value
    })
    
    // 2. 更新会话表中的回答者ID
    await updateConversationExpert({
      id: activeConversationId.value,
      expertId: currentUserId
    })
    
    answerInput.value = ''
    replyTarget.value = null
    
    // 3. 刷新消息和会话列表
    await fetchMessages(activeConversationId.value)
    await fetchConversations()
    
    ElMessage.success('回答提交成功')
    
  } catch (error) {
    console.error('❌ 提交回答失败:', error)
    ElMessage.error('提交回答失败：' + error.message)
  }
}

// 页面加载时初始化
onMounted(async () => {
  await fetchConversations()
  // 如果有会话，默认选择最新的一个
  if (conversations.value.length > 0) {
    await switchConversation(conversations.value[0].id)
  }
})
</script>

<style scoped>
.chat-container {
  display: flex;
  width: 100%;
  height: 600px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 左侧会话列表 */
.conversation-sidebar {
  width: 300px;
  background: #f8f9fa;
  border-right: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 15px;
  background: #fff;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.conversation-item {
  padding: 12px;
  margin-bottom: 8px;
  background: #fff;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.conversation-item:hover {
  background: #e3f2fd;
  transform: translateX(4px);
}

.conversation-item.active {
  background: #2196F3;
  color: #fff;
  border-color: #1976D2;
}

.conversation-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.conversation-title {
  font-weight: 600;
  font-size: 14px;
}

.conversation-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  opacity: 0.8;
}

.status {
  padding: 2px 6px;
  border-radius: 12px;
  font-size: 11px;
}

.status.open {
  background: #fff3cd;
  color: #856404;
}

.status.answered {
  background: #d4edda;
  color: #155724;
}

.status.closed {
  background: #f8d7da;
  color: #721c24;
}

.conversation-item.active .status {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

/* 右侧聊天区域 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  gap: 10px;
  padding: 15px;
  background: #fff;
  border-bottom: 1px solid #e9ecef;
}

.chat-body {
  flex: 1;
  overflow-y: auto;
  background: #f0f8f0;
  padding: 15px;
}

.welcome-message, .no-messages {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.welcome-message p:first-child {
  font-size: 18px;
  margin-bottom: 10px;
}

.chat-message {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chat-message.asker .bubble {
  align-self: flex-start;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.chat-message.expert .bubble {
  align-self: flex-end;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: #fff;
}

.bubble {
  padding: 12px 16px;
  border-radius: 18px;
  max-width: 70%;
  word-wrap: break-word;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.sender {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
  padding: 0 8px;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 5px;
  padding: 0 8px;
}

.chat-message.asker .sender,
.chat-message.asker .message-time {
  align-self: flex-start;
}

.chat-message.expert .sender,
.chat-message.expert .message-time {
  align-self: flex-end;
}

.reply-box {
  margin-top: 10px;
  padding: 15px;
  background: #fff;
  border-radius: 12px;
  border: 2px solid #e3f2fd;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

/* 自定义滚动条 */
.conversation-list::-webkit-scrollbar,
.chat-body::-webkit-scrollbar {
  width: 6px;
}

.conversation-list::-webkit-scrollbar-track,
.chat-body::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.conversation-list::-webkit-scrollbar-thumb,
.chat-body::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.conversation-list::-webkit-scrollbar-thumb:hover,
.chat-body::-webkit-scrollbar-thumb:hover {
  background: #999;
}
</style>